package com.chrome2sms.appengine;

import java.io.IOException;
import java.util.logging.Logger;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.http.*;

import org.mortbay.log.Log;

import com.google.android.c2dm.server.C2DMessaging;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;

@SuppressWarnings("serial")
public class Chrome2smsAppEngineServlet extends HttpServlet {
	
	private static final String ERROR_STATUS = "ERROR";
	private static final String DEVICE_NOT_REGISTERED_STATUS = "DEVICE_NOT_REGISTERED";
	private static final String OK_STATUS = "OK";
	private static final String LOGIN_REQUIRED_STATUS = "LOGIN_REQUIRED";
	
	private static final Logger log =
        Logger.getLogger(Chrome2smsAppEngineServlet.class.getName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.getWriter().println("Hello, world");
	}
	
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		resp.setContentType("text/plain");
		
		String message = req.getParameter("message");
		String phoneNumber = req.getParameter("phoneNumber");
		if (phoneNumber == null){
			resp.setStatus(400);
			resp.getWriter().println(ERROR_STATUS + " Phone number not specified");
			return;
		} else if (message == null){
			resp.setStatus(400);
			resp.getWriter().println(ERROR_STATUS + " Message cannot be empty");
			return;
		}
		
		User user = RegisterServlet.checkUser(req, resp, false);
		if (user != null){
			sendToPhone(message, phoneNumber, user.getEmail(), resp);
		} else{
			resp.getWriter().println(LOGIN_REQUIRED_STATUS);
		}
	}
	
	private boolean sendToPhone(String message, String phoneNumber,
			String userAccount, HttpServletResponse resp) throws IOException{
		
		DeviceInfo deviceInfo = null;
		
		PersistenceManager pm = C2DMessaging.getPMF(getServletContext()).getPersistenceManager();
		try{
			Key key = KeyFactory.createKey(DeviceInfo.class.getSimpleName(), userAccount);
			try{
				deviceInfo = pm.getObjectById(DeviceInfo.class, key);
			} catch (JDOObjectNotFoundException e){
				log.warning("Device Not Registered");
				resp.getWriter().println(DEVICE_NOT_REGISTERED_STATUS);
				return false;
			}
		} finally{
			pm.close();
		}
		
		C2DMessaging push = C2DMessaging.get(getServletContext());
		boolean res = false;
		String collapseKey = "" + message.hashCode();
		if (deviceInfo.getDebug()){
			res = push.sendNoRetry(deviceInfo.getDeviceRegistrationID(), 
					collapseKey, 
					"message", message,
					"phoneNumber", phoneNumber,
					"debug", "1");
		} else{
			res = push.sendNoRetry(deviceInfo.getDeviceRegistrationID(), 
					collapseKey, 
					"message", message,
					"phoneNumber", phoneNumber);
		}
		if (res){
			Log.info("Message sent to device! Hash: " + collapseKey);
			resp.getWriter().println(OK_STATUS);
			return true;
		} else{
			log.warning("Unable to send message to the device");
			resp.setStatus(500);
			resp.getWriter().println(ERROR_STATUS + " unable to send message to phone");
			return false;
		}
	}
}
